<template>
  <div class="page">
    <div class="flex-between" style="margin-bottom: 16px">
      <rj-space>
        <a-button type="primary" @click="addLicense()">{{
          $t('common.add')
        }}</a-button>
      </rj-space>
      <rj-space v-if="isExitLicense">
        <!-- <a-tooltip placement="right">
          <template slot="title">
            <span>{{ $t('flowControl.tip1') }}</span>
          </template>
          <a-icon
            type="question-circle"
            style="margin-left: 8px; color: #8c8c8c; font-size: 16px"
          />
        </a-tooltip> -->
        <span
          >{{ $t('license.state4') }}
          <a-tooltip placement="right">
            <template slot="title">
              <span>{{ $t('license.totaltip') }}</span>
            </template>
            <a-icon type="question-circle" style="color: #bfbfbf" />
          </a-tooltip>
          ：
          <span
            class="normal-tip fontweight"
            v-if="licenseStatus.currentStatus !== 'out-service'"
            >{{ $t('license.state1') }}</span
          >
          <span class="error-tip fontweight" v-else>{{
            $t('license.state2')
          }}</span>
        </span>

        <i18n path="license.state4" tag="span">
          <template slot="status">
            <span
              class="normal-tip fontweight"
              v-if="licenseStatus.currentStatus !== 'out-service'"
              >{{ $t('license.state1') }}</span
            >
            <span class="error-tip fontweight" v-else>{{
              $t('license.state2')
            }}</span>
          </template>
        </i18n>
        <span
          >{{
            $t('license.state5', {
              time: dealTime(licenseStatus.estimateTerminationTime),
            })
          }}
        </span>
        <span v-if="licenseStatus.currentStatus !== 'out-service'"
          >{{
            $t('license.state6', {
              time: getTime(),
            })
          }}
        </span>

        <i18n path="license.state7" tag="span">
          <template slot="total">
            <span class="fontweight"
              >{{ licenseStatus.usedPackage }}/
              {{ licenseStatus.totalPackage }}</span
            ></template
          >
        </i18n>
      </rj-space>
    </div>
    <rj-table
      class="upgrade-device-list"
      :columns="columns"
      :data-source="licenses"
      :rowKey="(row) => row.sn"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="time" slot-scope="text">
        {{ dealTime(text) }}
      </template>
      <template slot="opert" slot-scope="text, record">
        <a-popconfirm
          :title="$t('license.deleteTip')"
          @confirm="delLicense(record)"
        >
          <a-icon type="delete" class="question-icon"
        /></a-popconfirm>
      </template>
    </rj-table>

    <LicenseToal></LicenseToal>
    <rj-modal
      :title="$t('license.addTitle')"
      :visible="visible"
      :maskClosable="false"
      :width="600"
      :footer="null"
      @cancel="handelModalCancel"
    >
      <div class="export-license">
        <div class="step-cls" style="margin-top: -8px">
          1. {{ $t('license.step1') }}
        </div>
        <a-form-model
          :model="formModel"
          :wrapper-col="wrapperCol"
          :rules="rules"
          ref="ruleForm"
        >
          <a-form-model-item prop="licenseKey" label="">
            <a-input
              v-model="formModel.licenseKey"
              :placeholder="$t('license.keyvalidate')"
            />
          </a-form-model-item>
        </a-form-model>
        <a-button type="primary" @click="getLicense">{{
          $t('license.step2')
        }}</a-button>
      </div>

      <div>
        <div class="step-cls">2. {{ $t('license.step2') }}</div>
        <div>{{ $t('license.step2tip1') }}</div>
        <div>{{ $t('license.step2tip2') }}</div>
      </div>
      <div class="box">
        <div class="step-cls">3. {{ $t('license.step3') }}</div>
        <a-upload
          :multiple="false"
          list-type="picture-card"
          :show-upload-list="false"
          :fileList="fileList"
          class="avatar-uploader"
          :before-upload="beforeUpload"
          :accept="accept.toString()"
        >
          <a-button type="primary">{{ $t('license.import') }}</a-button>
        </a-upload>
      </div>
    </rj-modal>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import {
  requestHttp,
  maccApi,
  requestHttpDownload,
  requestHttpUpload,
} from '@utils/index';
import { RjTable, RjModal } from '@components';
import { i18nRender } from '@/locales';
import moment from 'moment-timezone';

import LicenseToal from './licenseToal';
const COLUMNS = [
  {
    title: i18nRender('license.tablicense'),
    dataIndex: 'sn',
    key: 'sn',
  },
  {
    title: i18nRender('license.tabnum'),
    dataIndex: 'productCode',
    key: 'productCode',
  },
  {
    title: i18nRender('license.tabpoduct'),
    dataIndex: 'productDesc',
  },
  {
    title: i18nRender('license.tabtime'),
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'time' },
  },
  {
    title: i18nRender('common.action'),
    dataIndex: 'opert',
    scopedSlots: { customRender: 'opert' },
  },
];

export default {
  name: 'license',
  props: {},
  components: {
    'rj-table': RjTable,
    'rj-modal': RjModal,
    LicenseToal: LicenseToal,
  },
  data() {
    let validateName = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('license.keySpace')));
      }
      let reg = false;
      let deviceNameRegex = /^[\w\-.]+$/;
      if (deviceNameRegex.test(value)) {
        let strByteLen = value.length;
        if (strByteLen >= 28 && strByteLen <= 64) {
          reg = true;
        }
      }
      if (!reg) {
        return callback(new Error(this.$t('license.keyvalidate')));
      }
      callback();
    };
    return {
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
      columns: COLUMNS,
      selectedRowKeys: [],
      selectedRows: [],
      licenses: [],
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10,
      },
      searchParam: {
        auth_type: '',
        online_status: '',
        account: '',
      },
      visible: false,
      formModel: {
        licenseKey: '',
      },
      rules: {
        licenseKey: [
          {
            required: true,
            validator: validateName,
            trigger: 'blur',
          },
        ],
      },
      accept: ['.lic'], //上传类型
      fileList: [],
      isExitLicense: false,
      licenseStatus: {
        tenantId: 40,
        usedPackage: 0, // 已使用服务包数
        unusedPackage: 204000, // 未使用服务包数,
        totalPackage: 204000, // 服务包总数
        currentMonthUsingPackage: 0,
        currentStatus: 'out-service',
        activeTime: 1561910400000,
        currentMonth: 1559318400000,
        estimateTerminationTime: 2098454400000, // 预估到期时间
      },
    };
  },

  mounted() {
    this.timezone = this.$store.state.User.userInfo.timeZone;
    this.initView();
  },
  created() {},
  methods: {
    initView() {
      this.getList();
      this.getLicenseStatus();
    },
    handleTableChange(pagination) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      this.pagination = pager;
      this.getList();
    },
    /**
     *
     * 获取列表
     * */
    async getList() {
      const ret = await requestHttp({
        api: `${maccApi.LICENSE_GET_API}?page=${this.pagination.current}&per_page=${this.pagination.pageSize}`,
        method: 'GET',
      });
      if (ret.code == 0) {
        this.licenses = ret.dataList;
        this.pagination.total = ret.totalCount;
      } else {
        this.licenses = [];
        this.pagination.total = 0;
      }
    },
    async getLicenseStatus() {
      const ret = await requestHttp({
        api: `${maccApi.LICENSE_OPLIC_SUMMARY_API}`,
        method: 'GET',
      });
      if (ret.code == 0) {
        if (ret.data) {
          this.isExitLicense = true;
          this.licenseStatus = ret.data;
        } else {
          this.isExitLicense = false;
        }
      }
    },
    dealTime(value) {
      return moment(value).tz(this.timezone).format('YYYY/MM/DD HH:mm:ss');
    },
    getTime() {
      if (this.licenseStatus.estimateTerminationTime) {
        let time =
          this.licenseStatus.estimateTerminationTime - new Date().getTime();
        if (time > 0) {
          //在线时长,默认单位s
          let activeTime = parseInt(time / 1000);
          let hour = Math.floor(activeTime / 3600);
          activeTime = activeTime % 3600;
          let minute = Math.floor(activeTime / 60);
          activeTime = activeTime % 60;
          let second = activeTime;
          return hour + 'h ' + minute + 'm ' + second + 's';
        }
      }
      return '--';
    },
    async delLicense(record) {
      const ret = await requestHttp({
        api: `${maccApi.LICENSE_DELETE_API.replace('{code}', record.sn)}`,
        method: 'DELETE',
      });
      if (ret.code == 0) {
        this.$message.success(this.$t('common.delSuccess'));
        this.getList();
      } else {
        this.$message.success(ret.msg);
      }
    },
    /**
     * 获取下载接口的data
     */
    getDownloadData() {
      let api = `${maccApi.LICENSE_CREATE_API.replace(
        '{sn}',
        this.form.licenseKey
      )}`;
      let data = {
        api: api,
        fileName: 'License.dat',
        attachment: true, //是否以附件形式下载，默认true
        method: 'GET',
        module: 'default', //api模块，用于区分service 部署的ip,不传默认default，非/service/api/的模块都需要传该参数，巡检--inspection，日志--logbiz，终端管理--pyservice

        contentType: 'application/dat;charset=UTF-8',
      };
      return data;
    },
    //直接下载License
    downloadLicense(id) {
      let data = this.getDownloadData(id);
      requestHttpDownload(JSON.stringify(data)).then((ret) => {
        //真正下载
        let url = '/webproxy/common/file/download';
        let downloadData = ret.data.downloadData;
        url += '?downloadData=' + downloadData;
        window.open(url);
      });
    },
    async addLicense() {
      this.visible = true;
    },
    getLicense() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.downloadLicense();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    beforeUpload(file) {
      const fileNames = file.name.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      if (this.accept.indexOf(fileType) > -1) {
        this.fileName = file.name;
        this.fileUrl = window.URL.createObjectURL(file);
        this.fileList = [file];
        //自定义上传
      } else {
        this.$message.warning(this.$t('components.excelImport.upfailfailure'));
      }
      return false;
    },
    async importLicense() {
      let fileName = encodeURIComponent(this.fileName);
      let api = `${maccApi.LICENSE_IMPORT_API}?file_name=${fileName}`;
      this.uploadData = {
        uploadData: JSON.stringify({
          api: api,
          method: 'POST',
          module: 'default',
          // contentType: 'application/octet-stream', //此接口必须设置contentType
          contentType: 'multipart/form-data', //此接口必须设置contentType
        }),
      };
      this.loading = true;
      let params = {
        file: this.fileList[0],
        uploadData: this.uploadData.uploadData,
      };

      let res = await requestHttpUpload(params);
      if (res && res.code == 0) {
        this.fileList = [];
        this.visible = false;
        this.$message.success(this.$t('components.excelImport.importsuccess'));
        this.getList();
      } else {
        this.$message.error(res.msg);
      }
    },
    handelModalCancel() {
      this.visible = false;
    },
  },
  watch: {
    fileList() {
      if (this.fileList.length > 0) {
        this.importLicense();
      }
    },
  },
  computed: {
    ...mapState('Group', ['groupId']),
  },
};
</script>
<style lang="less" scoped>
.page {
  padding: 16px;
}
.flex-between {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
.normal-tip {
  color: @success-color;
}
.error-tip {
  color: @error-color;
}
.fontweight {
  font-weight: bold;
}
.export-license {
  /deep/.ant-form-item {
    margin-bottom: 8px;
  }
}
.step-cls {
  margin-top: 8px;
  font-weight: bold;
}
.box {
  /deep/ .ant-upload-picture-card-wrapper {
    width: 160px;
  }
  /deep/ .ant-upload.ant-upload-select-picture-card {
    width: 104px;
    height: 32px;
  }
  /deep/ .ant-upload {
    padding: 0px;
    background-color: #fff;
    border: 0px;
    margin-left: -16px;
    margin-top: 8px;
  }
}
</style>
